<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/5
 * Time: 13:28
 */
namespace app\api\controller;

use app\common\traits\ApiServiceTrait;
use think\Controller;
use think\exception\ValidateException;

class BaseController extends Controller
{
    use ApiServiceTrait;

    //验证器验证失败后自动抛出异常,配合异常接管类自动返回json格式数据,不要修改基类的此属性！！
    protected $failException = true;

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        global $errCode ;
        $errCode = $this->CODE_SUCCESS;
        global $errMsg ;
        $errMsg = 'SUCCESS';
    }

    /**
     * @name: 获取数据
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-11-06 17:08:41
     */
    public function filterInput ()
    {
        $inputData = file_get_contents('php://input', 'r');

        $postData = json_decode($inputData, true);
        if (empty($postData))
        {
           throw new ValidateException("JSON 错误 !!", 422);
        }
        $controller = strtolower(request()->controller());
        $action =  strtolower(request()->action());
        //命令回调接口,则logId必填
        if(strpos($controller,'.') !== false){
            $firstController = substr($controller,0,strpos($controller,'.'));
        }else{
            $firstController = $controller;
        }
        if($firstController == 'directive' && (!isset($postData['logId']) || !is_numeric($postData['logId']) || $postData['logId'] <= 0)){
            throw new ValidateException('数据错误 缺少必须参数logId', 422);
        }
        if(isset($postData['logId'])){
            global $logId;
            $logId = $postData['logId'];
        }

        if($controller == 'clientregister' && $action == 'reg'){
            //登录
            if(!isset($postData['host_info']) ){
               throw new ValidateException('数据错误 缺少主机信息', 422);
            }
        }else{
            //非登录
            if (!isset($postData['hostkey'])) {
               throw new ValidateException('数据错误 缺少绑定码信息', 422);
            }
        }

        if (!isset($postData['version'])) {
           throw new ValidateException('数据错误 缺少版本号', 422);
        }

        global $online_host;
        $online_host = [];
        if (isset($postData['host_id']))
        {
            $online_host[$postData['host_id']] = [
                'id' => $postData['host_id'],
            ];
        }


        return $postData;
    }

    /**
     * @name 添加日志记录
     * @param $path
     * @param $data
     * @author wx
     * @date 2021/1/4 11:16
     */
    public function addRuntimeLog($path, $data)
    {
        //1. 判断大小,如果超过5M就删除
        if (file_exists($path) && filesize($path) >= 5 * 1024 * 1024 * 1024) {
            unlink($path);
        }

        $logData = date('Y-m-d H:i:s').'---'.$_SERVER['REMOTE_ADDR'].PHP_EOL.$data.PHP_EOL;

        file_put_contents($path, $logData,FILE_APPEND);
    }

}